import cloud from '@lafjs/cloud'

/**
 * 记录操作日志
 * @param ctx
 * @constructor
 */
const db = cloud.database()

export async function RequestLog(ctx:FunctionContext) {
  const ip = ctx.headers['x-real-ip'] ? ctx.headers['x-real-ip'] : ctx.headers['x-forwarded-for']
  if (ip == "null") {
    ctx.response.status(403);
    ctx.response.json({ "code": 403, "msg": "访问受限，请联系管理员" })
    return false
  }
  // @ts-ignore
  const func = ctx.request.params.name
  const referer = ctx.headers['referer']
  const userAgent = ctx.headers['user-agent']
  const requestId = ctx.requestId
  // 添加请求IP到数据库，并自动添加 add_time

  let requestIp = {
    requestId: requestId,
    ip: ip,
    referer: referer,
    userAgent: userAgent,
    func: func,
    createdTime: new Date(),
    updatedTime: new Date(),
    userId:""
  }
  if (ctx.user){
    //已经登录的用户
    requestIp.userId = ctx.user.admin
  }

  await db.collection('requestIp').add(requestIp)

}
